﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.Reflection;
using System.Text;
using Caliburn.Micro;
using Zero.Common;

namespace Zero.Frontend
{
    /// <summary>
    /// Bootstrapper for Caliburn.Micro, that uses MEF for depdency resolution and injection.
    /// </summary>
    /// <typeparam name="T">Type of viewmodel to resolve after startup.</typeparam>
    public class MefBootstrapper<T> : Bootstrapper<T>
    {
        private CompositionContainer _container;

        protected CompositionContainer Containter { get { return _container; } }

        protected override void Configure()
        {
            _container = new CompositionContainer(
                new AggregateCatalog(
                    AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()
                    )
                );

            var batch = new CompositionBatch();

            ConfigureBatch(batch);

            batch.AddExportedValue(_container);

            _container.Compose(batch);
        }

        /// <summary>
        /// Override to specify concrete dependecies.
        /// </summary>
        /// <param name="batch"></param>
        protected virtual void ConfigureBatch(CompositionBatch batch)
        {            
        }

        protected override IEnumerable<Assembly> SelectAssemblies()
        {
            return base.SelectAssemblies().Union(new[]
                                                     {
                                                         typeof(EntityObject).Assembly, // Zero.Common assembly
                                                         typeof(MefBootstrapper<T>).Assembly // Zero.Common assembly
                                                     });
        }

        protected override object GetInstance(Type serviceType, string key)
        {
            string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
            var exports = _container.GetExportedValues<object>(contract);

            if (exports.Count() > 0)
                return exports.First();

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }

        protected override IEnumerable<object> GetAllInstances(Type serviceType)
        {
            return _container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
        }

        protected override void BuildUp(object instance)
        {
            _container.SatisfyImportsOnce(instance);
        }
    }
}
